import Editor from "../editor"
import { Operation } from './operation'
import InsertTextOperation from "./insert_text_operation";
import SetSelectionOperation from "./set_selection_operation";
export class RemoveTextOperation extends Operation {
    // 删除字符需要知道从哪里开始删除，删多少个
    // 因此需要 startIndex、endIndex
    private startIndex: number;
    private endIndex: number;
    /** 删除掉的字符, 用于撤销重做 */
    private spacers = '';
    constructor(private startIndex_: number, private endIndex_: number) {
        super()
        this.startIndex = startIndex_;
        this.endIndex = endIndex_;
    }
    apply(editor: Editor) {
        this.spacers = editor.getTextModel()?.getSpacersByIndex(this.startIndex, this.endIndex) || "";

        editor.getTextModel().remove(this.startIndex_, this.endIndex_);
    }
    inverse(editor: Editor) {
        // let { startIndex, endIndex } = this;

        // // 保证插入时始终是在开始位置插入(存在选区时开始位置可能大于结束位置)
        // if (startIndex > endIndex) {
        //     [startIndex, endIndex] = [endIndex, startIndex];
        // }
        // editor.getTextModel().insert(startIndex, this.spacers);

    }

    getIndex() {
        return { startIndex: this.startIndex, endIndex: this.endIndex };
    }

    reverse(): Operation[] {
        return [
            new InsertTextOperation(this.spacers, this.startIndex),
            new SetSelectionOperation({
                anchor: this.spacers.length === 1 ? this.startIndex + this.spacers.length : this.startIndex,
                focus: this.startIndex + this.spacers.length
            })
        ];
    }
}

export default RemoveTextOperation